package cn.net.mugui.web.lock;

import java.util.HashMap;
import java.util.concurrent.locks.ReentrantLock;

import javax.servlet.http.HttpSession;

import com.mugui.base.base.Autowired;
import com.mugui.base.base.Component;
import com.mugui.base.client.net.base.Filter;
import com.mugui.base.client.net.base.Listener;
import com.mugui.base.client.net.bean.Message;
import com.mugui.base.client.net.bean.NetBag;
import com.mugui.base.client.net.filter.FilterModel;
import com.mugui.base.client.net.listener.ListenerModel;

import cn.net.mugui.web.tomcat.SessionContext;

@Component
@Filter(weight = 98, value = { "*" }, type = Filter.POSITIVE)
@Listener(weight = 98, value = { "*" }, type = Filter.POSITIVE)

public class SynchronizeLock implements FilterModel, ListenerModel {
	public static byte[] lock = new byte[0];

	@Override
	public NetBag filter(NetBag bag) {
		return lock(bag);

	}

	@Autowired
	private GroupLockManager groupLockManager = null;

	private NetBag lock(NetBag bag) {
		String name = (String) groupLockManager.get(bag.getFunc());
		if (name == null)
			return bag;

		ReentrantLock key = null;
		HttpSession session = SessionContext.getSession(bag.getSession());
		if (session == null) {
			return bag;
		}
		synchronized (lock) {
			key = (ReentrantLock) session.getValue(name);
			if (key == null) {
				session.putValue(name, key = new ReentrantLock());
			}
		}
		if (key.isLocked()){
			bag.setData(Message.error("正在处理中2，请稍后").setType(429));
			return null;
		}
		key.lock();
		return bag;
	}

	@Override
	public void listener(Message message, NetBag bag) {
		String name = (String) groupLockManager.get(bag.getFunc());
		if (name == null)
			return;
		HttpSession session = null;
		if (null == (session = SessionContext.getSession(bag.getSession()))) {
			return;
		}
		ReentrantLock object = (ReentrantLock) session.getValue(name);
		if (object != null) {
			if (object.isHeldByCurrentThread())
				object.unlock();
		}

	}

}
